package com.wslds.blog.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.wslds.base.action.BaseAction;
import com.wslds.base.dao.page.PageAdapter;
import com.wslds.base.util.BlogCons;
import com.wslds.base.util.SessionUtil;
import com.wslds.bean.Tag;
import com.wslds.bean.ext.TaginstExt;
import com.wslds.blog.service.TagService;

@SuppressWarnings("serial")
@Component("tagAction")
@Scope("prototype")
public class TagAction extends BaseAction{

	private Tag tag;
	
	@Resource
	private TagService tagService;
	
	public String refreshTagCache(){
		
		TaginstExt tagParam = new TaginstExt();
		List<TaginstExt> taginstExt = tagService.getDao().findExt("tag_select_ext", tagParam);
		Map<Long,List<TaginstExt>> tagMap = new HashMap<Long,List<TaginstExt>>();
		for( TaginstExt taginst: taginstExt ){
			if( tagMap.containsKey(taginst.getArtId()) ){
				List<TaginstExt> list = tagMap.get(taginst.getArtId());
				list.add(taginst);
			}else{
				List<TaginstExt> list = new ArrayList<TaginstExt>();
				list.add(taginst);
				tagMap.put(taginst.getArtId(), list);
			}
		}
		SessionUtil.getServletContext().setAttribute(BlogCons.APPLICATION.TAGINST, tagMap);
		
		return SUCCESS;
	}
	
	public String listTag(){
		PageAdapter<Tag> adapter = tagService.getDao().page("tag", tag, getPage());
		this.put("adapter", adapter);
		return SUCCESS;
	}
	
	public String listAjaxTag(){
		PageAdapter<Tag> adapter = tagService.getDao().page("tag", tag, getPage());
		this.put("adapter", adapter);
		return SUCCESS;
	}
	
	public String insert(){
		tagService.getDao().save("tag", tag);
		
		SessionUtil.refreshTag();
		
		return SUCCESS;
	}
	
	public String toUpdate(){
		tag = tagService.getDao().findOne("tag", tag);
		return SUCCESS;
	}
	
	public String update(){
		tagService.getDao().update("tag", tag);
		
		SessionUtil.refreshTag();
		
		return SUCCESS;
	}

	public Tag getTag() {
		return tag;
	}

	public void setTag(Tag tag) {
		this.tag = tag;
	}


}
